<template>
  <div class="section">
    <div class="c_top">
      <div class="left-nav">
        <div class="optionShow">
          <el-button
            id="optionShow"
            type="text"
            icon="el-icon-guide"
            @click="centerDialogVisible = true"
          >操作说明</el-button>
        </div>
        <el-dialog title="步骤介绍" :visible.sync="centerDialogVisible" width="30%">
          <p>1、此时的拔高系数为3米；</p>
          <p>2、点击选取颜色，点击提交按钮，实现岩性着色；</p>
          <p>3、点击地层剖面按钮，生成地层模型的剖面；</p>
          <p>4、点击加载和清除模型，实现前端浏览器三维地层模型的展示。</p>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>
        <div class="optionShow">
          <el-button id="optionShow" type="text" icon="el-icon-setting">主要功能</el-button>
        </div>
        <div class="optionShow">
          <el-button id="optionShow" class="color" type="text" style=" padding-left: 15px;">
            <strong>1、</strong>岩性着色
          </el-button>
        </div>

        <!--岩性着色-->
        <div class="lithology">
          <label for="color-1">
            填土, 素填土:
            <input id="color-1" type="color" value="#FF7F00" />
          </label>
          <label for="color-2">
            黄土：
            <input id="color-2" type="color" value="#FFEC8B" />
          </label>
          <label for="color-3">
            古土壤:
            <input id="color-3" type="color" value="#8B7355" />
          </label>
          <label for="color-4">
            粉质粘土, 粉细砂：
            <input id="color-4" type="color" value="#EEDC82" />
          </label>
          <label for="color-5">
            卵石:
            <input id="color-5" type="color" value="#96CDCD" />
          </label>
          <label for="color-6">
            圆砾, 砾砂：
            <input id="color-6" type="color" value="#4682B4" />
          </label>
          <label for="color-7">
            中粗砂:
            <input id="color-7" type="color" value="#00CD00" />
          </label>
          <button id="color-change" @click="colorChange">提交</button>
        </div>
        <div class="optionShow">
          <el-button id="optionShow" class="color" type="text" style=" padding-left: 15px;">
            <strong>2、</strong>地层剖面
          </el-button>
        </div>
        <div>
          <button id="dc-section" @click="dcSection" style="margin-top:15px;">地层剖面</button>
          <button id="clean-section" @click="cleanSection" style="margin-top:15px;">清除剖面</button>
          <button id="stop-section" @click="stopSection" style="margin-top:15px;">停止绘制</button>
        </div>
        <div class="optionShow">
          <el-button id="optionShow" class="color" type="text" style=" padding-left: 15px;">
            <strong>3、</strong>模型加载
          </el-button>
        </div>
        <div style="margin-bottom:10px;">
          <button id="clean-model" @click="cleanModel" style="margin-top:15px;">清除模型</button>
          <button id="load-model" @click="loadModel" style="margin-top:15px;">加载模型</button>
        </div>
      </div>
      <div
        id="WebGL-output"
        class="webgl"
        v-loading="loading"
        element-loading-text="模型加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      ></div>
    </div>
    <div class="guid">
      <div class="guidBar">
        <el-button icon="el-icon-arrow-left" plain @click="previous">上一页</el-button>
        <el-button plain @click="nextStep">
          下一页
          <i class="el-icon-arrow-right el-icon--right"></i>
        </el-button>
      </div>
    </div>
  </div>
</template>
<script>
import * as THREE from "three/build/three.js";
import { TrackballControls } from "three/examples/js/controls/TrackballControls.js";
import { Notification } from "element-ui";
export default {
  name: "sec",
  data() {
    return {
      centerDialogVisible: true,
      gtpoints: [],
      clock: null,
      scene: null,
      webGLRenderer: null,
      controls: null,
      GTPGeometry: null,
      width: "",
      height: "",
      camera: null,
      h: 3.0,
      color1: "#FF7F00",
      color2: "#FFEC8B",
      color3: "#8B7355",
      color4: "#EEDC82",
      color5: "#96CDCD",
      color6: "#4682B4",
      color7: "#00CD00",
      sections: [],
      pointsArray: [],
      loading: false
    };
  },
  methods: {
    colorChange() {
      this.color1 = this.convertcolor(document.getElementById("color-1").value);
      this.color2 = this.convertcolor(document.getElementById("color-2").value);
      this.color3 = this.convertcolor(document.getElementById("color-3").value);
      this.color4 = this.convertcolor(document.getElementById("color-4").value);
      this.color5 = this.convertcolor(document.getElementById("color-5").value);
      this.color6 = this.convertcolor(document.getElementById("color-6").value);
      this.color7 = this.convertcolor(document.getElementById("color-7").value);
      document.getElementById("WebGL-output").innerHTML = "";
      this.init();
    },
    convertcolor(color) {
      color = color.replace("#", "0x");
      return parseInt(color);
    },
    dcSection() {
      let container = document.getElementById("WebGL-output");
      container.addEventListener("click", this.onMouseClick, false);
      container.addEventListener("mousemove", this.onMouseMove, false);
      container.style.cursor = "crosshair";
      var score = Math.round(Math.random() * 5) + 5;
      this.$store.dispatch("addthreeScoreByAction", score);
    },
    onMouseClick(event) {
      let container = document.getElementById("WebGL-output");
      event.preventDefault();
      var x =
        (event.clientX - container.getBoundingClientRect().left) /
          container.offsetWidth *
          2 -
        1;
      var y =
        -(
          (event.clientY - container.getBoundingClientRect().top) /
          container.offsetHeight
        ) *
          2 +
        1;
      var standardVector = new THREE.Vector3(x, y, 1);
      var worldVector = standardVector.unproject(this.camera);
      var ray = worldVector.sub(this.camera.position).normalize();
      var rayCaster = new THREE.Raycaster(this.camera.position, ray);
      var intersects = rayCaster.intersectObjects(this.scene.children, true);
      if (intersects.length > 0 && intersects[0].object.name == "gtp") {
        //若点击的是鼠标左键
        if (event.button == 0) {
          //创建点（Points）
          var pointsGeometry = new THREE.Geometry({
            vertices: intersects[0].point,
            colors: 0x0a0a0a
          });
          pointsGeometry.vertices.push(intersects[0].point);
          var pointsMaterial = new THREE.PointsMaterial({
            color: 0x0a0a0a,
            size: 20
          });

          var points = new THREE.Points(pointsGeometry, pointsMaterial);
          this.pointsArray.push(points);
          //创建线段
          var lineGeometry = new THREE.Geometry();
          var lineMaterial = new THREE.LineBasicMaterial({
            color: 0xff0000,
            linewidth: 15
          });
          if (this.pointsArray.length == 2) {
            lineGeometry.vertices.push(
              this.pointsArray[0].geometry.vertices[0],
              this.pointsArray[1].geometry.vertices[0]
            );
            //console.log(pointsArray[0].geometry.vertices[0], pointsArray[1].geometry.vertices[0]);
            var line = new THREE.Line(lineGeometry, lineMaterial);
            //执行添加剖面操作
            this.addSectionAjax(
              this.pointsArray[0].geometry.vertices[0],
              this.pointsArray[1].geometry.vertices[0]
            );
            //清空数组，并中断绘制
            this.pointsArray = [];
            this.scene.add(line);
          }
          this.scene.add(points);
        }
      }
    },
    addSectionAjax(p1, p2) {
      var x1 = p1.x + 2245;
      var y1 = p1.y + 1845;
      var x2 = p2.x + 2245;
      var y2 = p2.y + 1845;

      let param = new URLSearchParams();
      param.append("x1", x1);
      param.append("y1", y1);
      param.append("x2", x2);
      param.append("y2", y2);

      this.$axios
        .post(
          "http://192.168.3.165:3102/dcvir/getSectionByCoordinate4",
          param,
          {
            emulateJSON: true
          },
          { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
        )
        .then(res => {
          this.sections = res.data;
          this.addSection();
        })
        .catch(console.log);
    },
    addSection() {
      for (let i in this.sections) {
        var section = this.sections[i];
        var vertices = new Float32Array([
          section.x1 - 2245,
          section.y1 - 1845,
          (section.z1 - 382) * this.h + 400,
          section.x2 - 2245,
          section.y2 - 1845,
          (section.z2 - 382) * this.h + 400,
          section.x3 - 2245,
          section.y3 - 1845,
          (section.z3 - 382) * this.h + 400,
          section.x4 - 2245,
          section.y4 - 1845,
          (section.z4 - 382) * this.h + 400
        ]);
        var indexes = new Uint16Array([0, 1, 2, 1, 2, 3]);

        var SectionGeometry = new THREE.BufferGeometry();
        SectionGeometry.addAttribute(
          "position",
          new THREE.BufferAttribute(vertices, 3)
        );

        SectionGeometry.index = new THREE.BufferAttribute(indexes, 1);

        if (section.sid == 1) {
          var sectionMaterial = new THREE.MeshBasicMaterial({
            color: this.color1,
            side: THREE.DoubleSide
          });
        }
        if (section.sid == 2) {
          var sectionMaterial = new THREE.MeshBasicMaterial({
            color: this.color2,
            side: THREE.DoubleSide
          });
        }
        if (section.sid == 3) {
          var sectionMaterial = new THREE.MeshBasicMaterial({
            color: this.color3,
            side: THREE.DoubleSide
          });
        }
        if (section.sid == 4) {
          var sectionMaterial = new THREE.MeshBasicMaterial({
            color: this.color4,
            side: THREE.DoubleSide
          });
        }
        if (section.sid == 5) {
          var sectionMaterial = new THREE.MeshBasicMaterial({
            color: this.color5,
            side: THREE.DoubleSide
          });
        }
        if (section.sid == 6) {
          var sectionMaterial = new THREE.MeshBasicMaterial({
            color: this.color6,
            side: THREE.DoubleSide
          });
        }
        if (section.sid == 7) {
          var sectionMaterial = new THREE.MeshBasicMaterial({
            color: this.color7,
            side: THREE.DoubleSide
          });
        }

        var SectionMesh = new THREE.Mesh(SectionGeometry, sectionMaterial); //var GTPMesh = new THREE.Mesh(GTPGeometry, material);
        SectionMesh.name = "section";
        this.scene.add(SectionMesh);
      }
      this.sections = [];
    },
    onMouseMove(event) {
      let container = document.getElementById("WebGL-output");
      event.preventDefault();
      var x =
        (event.clientX - container.getBoundingClientRect().left) /
          container.offsetWidth *
          2 -
        1;
      var y =
        -(
          (event.clientY - container.getBoundingClientRect().top) /
          container.offsetHeight
        ) *
          2 +
        1;
      var standardVector = new THREE.Vector3(x, y, 1);
      var worldVector = standardVector.unproject(this.camera);
      var ray = worldVector.sub(this.camera.position).normalize();
      var rayCaster = new THREE.Raycaster(this.camera.position, ray);
      var intersects = rayCaster.intersectObjects(this.scene.children, true);
      if (intersects.length > 0 && intersects[0].object.name == "gtp") {
        //鼠标左键未点击时线段的移动状态
        if (this.scene.getObjectByName("line_move")) {
          this.scene.remove(this.scene.getObjectByName("line_move"));
        }
        //创建线段
        var lineGeometry = new THREE.Geometry();
        var lineMaterial = new THREE.LineBasicMaterial({
          color: 0xff0000,
          linewidth: 15
        });
        if (this.pointsArray.length == 1) {
          lineGeometry.vertices.push(this.pointsArray[0].geometry.vertices[0]);
          var mouseVector3 = new THREE.Vector3(
            intersects[0].point.x,
            intersects[0].point.y,
            intersects[0].point.z
          );
          lineGeometry.vertices.push(mouseVector3);
          var line = new THREE.Line(lineGeometry, lineMaterial);
          line.name = "line_move";
          this.scene.add(line);
        }
      }
    },
    stopSection() {
      let container = document.getElementById("WebGL-output");
      container.removeEventListener("click", this.onMouseClick);
      container.removeEventListener("mousemove", this.onMouseMove);
      container.style.cursor = "default";
    },
    cleanSection() {
      this.removePoints();
      this.removeLines();
      var allChildren = this.scene.children;
      var numObjects = this.scene.children.length;
      for (var i = 0; i < numObjects; i++) {
        var object = allChildren[i];
        if (object.name == "section") {
          this.scene.remove(object);
          i--;
        }
      }
    },
    removePoints() {
      var distance = 0;
      var allChildren = this.scene.children;
      var numObjects = this.scene.children.length;
      //var lastObject = allChildren[allChildren.length-1];
      for (var i = 0; i < numObjects; i++) {
        var object = allChildren[i];
        if (object instanceof THREE.Points) {
          this.scene.remove(object);
          i--;
        }
      }
    },
    removeLines() {
      var distance = 0;
      var allChildren = this.scene.children;
      var numObjects = this.scene.children.length;
      for (var i = 0; i < numObjects; i++) {
        var object = allChildren[i];
        if (object instanceof THREE.Line) {
          this.scene.remove(object);
          i--;
        }
      }
    },
    cleanModel() {
      var allChildren = this.scene.children;
      var numObjects = this.scene.children.length;
      for (var i = 0; i < numObjects; i++) {
        var object = allChildren[i];
        if (object.name == "gtp") {
          object.material.visible = false;
        }
      }
    },
    loadModel() {
      var allChildren = this.scene.children;
      var numObjects = this.scene.children.length;
      for (var i = 0; i < numObjects; i++) {
        var object = allChildren[i];
        if (object.name == "gtp") {
          object.material.visible = true;
        }
      }
    },
    init() {
      let container = document.getElementById("WebGL-output");
      this.width = container.clientWidth;
      this.height = container.clientHeight;
      this.camera = new THREE.PerspectiveCamera(
        60,
        this.width / this.height,
        100,
        12000
      );
      //初始为斜视
      this.camera.position.x = 0;
      this.camera.position.y = 4000;
      this.camera.position.z = 2250;
      this.camera.lookAt(new THREE.Vector3(0, 0, 0));
      this.camera.up.x = 0;
      this.camera.up.y = 0;
      this.camera.up.z = 1;
      this.clock = new THREE.Clock();
      this.scene = new THREE.Scene();
      this.scene.background = new THREE.Color(0xebebeb);
      this.webGLRenderer = new THREE.WebGLRenderer({
        antialias: true
      });
      this.webGLRenderer.setSize(this.width, this.height);
      this.controls = new THREE.TrackballControls(this.camera, container);
      this.controls.rotateSpeed = 1.0;
      this.controls.zoomSpeed = 1.5;
      this.controls.panSpeed = 1.0;
      this.controls.staticMoving = true;
      this.controls.dynamicDampingFactor = 0.3;
      container.appendChild(this.webGLRenderer.domElement);
      for (let i in this.gtpoints) {
        var gtpoint = this.gtpoints[i];
        var vertices = new Float32Array([
          gtpoint.x1 - 2245,
          gtpoint.y1 - 1845,
          (gtpoint.z1 - 382) * this.h,
          gtpoint.x2 - 2245,
          gtpoint.y2 - 1845,
          (gtpoint.z2 - 382) * this.h,
          gtpoint.x3 - 2245,
          gtpoint.y3 - 1845,
          (gtpoint.z3 - 382) * this.h,
          gtpoint.x4 - 2245,
          gtpoint.y4 - 1845,
          (gtpoint.z4 - 382) * this.h,
          gtpoint.x5 - 2245,
          gtpoint.y5 - 1845,
          (gtpoint.z5 - 382) * this.h,
          gtpoint.x6 - 2245,
          gtpoint.y6 - 1845,
          (gtpoint.z6 - 382) * this.h
        ]);
        var indexes = new Uint16Array([
          0,
          1,
          2,
          3,
          4,
          5,
          0,
          1,
          3,
          1,
          3,
          4,
          1,
          2,
          4,
          2,
          4,
          5,
          0,
          2,
          3,
          2,
          3,
          5
        ]);
        this.GTPGeometry = new THREE.BufferGeometry();
        this.GTPGeometry.addAttribute(
          "position",
          new THREE.BufferAttribute(vertices, 3)
        );
        this.GTPGeometry.addAttribute(
          "soil",
          new THREE.BufferAttribute(gtpoint.sid, 1)
        );
        this.GTPGeometry.index = new THREE.BufferAttribute(indexes, 1);
        if (gtpoint.sid == 1) {
          var material = new THREE.MeshBasicMaterial({
            color: this.color1,
            side: THREE.DoubleSide
          });
        }
        if (gtpoint.sid == 2) {
          var material = new THREE.MeshBasicMaterial({
            color: this.color2,
            side: THREE.DoubleSide
          });
        }
        if (gtpoint.sid == 3) {
          var material = new THREE.MeshBasicMaterial({
            color: this.color3,
            side: THREE.DoubleSide
          });
        }
        if (gtpoint.sid == 4) {
          var material = new THREE.MeshBasicMaterial({
            color: this.color4,
            side: THREE.DoubleSide
          });
        }
        if (gtpoint.sid == 5) {
          var material = new THREE.MeshBasicMaterial({
            color: this.color5,
            side: THREE.DoubleSide
          });
        }
        if (gtpoint.sid == 6) {
          var material = new THREE.MeshBasicMaterial({
            color: this.color6,
            side: THREE.DoubleSide
          });
        }
        if (gtpoint.sid == 7) {
          var material = new THREE.MeshBasicMaterial({
            color: this.color7,
            side: THREE.DoubleSide
          });
        }
        var GTPMesh = new THREE.Mesh(this.GTPGeometry, material); //var GTPMesh = new THREE.Mesh(GTPGeometry, material);
        GTPMesh.name = "gtp";
        this.scene.add(GTPMesh);
        var wirematerial = new THREE.MeshBasicMaterial({ wireframe: true });
        var GTPWire = new THREE.Mesh(this.GTPGeometry, wirematerial);
        GTPWire.name = "gtp";
        this.scene.add(GTPWire);
      }
      this.render();
      //添加window窗口调整监听事件
      window.addEventListener("resize", this.onWindowResize, false);
    },
    render() {
      var delta = this.clock.getDelta();
      this.controls.update(delta);
      requestAnimationFrame(this.render);
      this.webGLRenderer.render(this.scene, this.camera);
    },
    onWindowResize() {
      this.camera.aspect = this.width / this.height;
      this.camera.updateProjectionMatrix();
      this.webGLRenderer.setSize(this.width, this.height);
      this.controls.handleResize();
      this.render();
    },
    previous() {
      this.$router.go(-1);
    },
    nextStep() {
      this.$router.push({ name: "zk" });
    }
  },
  created() {
    this.loading = true;
    this.$axios
      .post("http://192.168.3.165:3102/dcvir/getData")
      .then(res => {
        this.loading = false;
        this.gtpoints = res.data;
        console.log(res.data);
        this.init();
        Notification.success({
          message: "模型加载完成!",
          duration: 2000,
          position: "bottom-right"
        });
      })
      .catch(console.log);
  }
};
</script>
<style lang="less" scoped>
.section {
  margin: 30px 0 15px 0;
  .c_top {
    padding: 0 0 0 20px;
    display: flex;
    justify-content: space-between;
    .left-nav {
      height: 100%;
      width: 205px;
      padding: 10px 10px;
      background-color: #fff;
      border: 1px solid #eaeaea;
      .optionShow {
        width: 100%;
        height: 35px;
        border-bottom: 1px dashed #eaeaea;
        .color {
          color: #333;
        }
        #optionShow {
          width: 100%;
          text-align: left;
          padding: 0;
          padding-left: 5px;
          line-height: 35px;
        }
      }
      .lithology {
        margin-top: 15px;
        label {
          font-size: 14px;
          display: flex;
          justify-content: space-between;
          height: 35px;
          margin-bottom: 15px;
          line-height: 35px;
          input {
            line-height: 21px;
            width: 32%;
            height: 35px;
            padding: 5px;
            -webkit-user-select: text;
            border: 1px solid rgba(0, 0, 0, 0.2);
            border-radius: 3px;
            outline: 0;
            background-color: #fff;
            -webkit-appearance: none;
          }
        }
        #color-change {
          width: 100%;
          border: 1px solid #409eff;
          color: #409eff;
        }
      }
    }
    .webgl {
      height: 750px;
      width: 85%;
    }
  }
  .guid {
    width: 100%;
    .guidBar {
      display: flex;
      justify-content: space-between;
      width: 250px;
      height: 40px;
      margin: 15px auto 0;
    }
  }
}
</style>


